
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.S;
using Apps.Models.S;
using Apps.IBLL.S;
using Apps.DAL.S;

namespace Apps.BLL.S
{
    public partial class S_SAMPLE_CHECKBLL : Virtual_S_SAMPLE_CHECKBLL, IS_SAMPLE_CHECKBLL
    {
        
    }
    public class Virtual_S_SAMPLE_CHECKBLL
	{
        [Dependency]
        public IS_SAMPLE_CHECKRepository m_Rep { get; set; }

        [Dependency]
        public S_SAMPLE_CHECKDETAILRepository m_DetailRep { get; set; }
        public virtual List<S_SAMPLE_CHECKModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<S_SAMPLE_CHECK> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
								a=>a.CHECK_ID.Contains(queryStr)
								
								
								|| a.CHECK_USER_ID.Contains(queryStr)
								
								
								
								|| a.REMARKS.Contains(queryStr)
								
								|| a.TEMPLATE_ID.Contains(queryStr)
								
								);
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }
		 
		public virtual List<S_SAMPLE_CHECKModel> GetPagerList(ref GridPager pager, Expression<Func<S_SAMPLE_CHECK, bool>> whereLambda )
        {
            try
            {
                //using (DBContainer db = new DBContainer())
                //{
                    //var queryData = from m1 in db.S_SAMPLE_CHECK
                    //                join m2 in db.SysUser on m1.CHECK_USER_ID equals m2.Id
                    //                select new S_SAMPLE_CHECKModel()
                    //                {
                    //                    APPROVAL_STATUS = m1.APPROVAL_STATUS,
                    //                    CHECK_USER_ID = m1.CHECK_USER_ID,
                    //                    CHECK_ID = m1.CHECK_ID,
                    //                    CHECK_MODE = m1.CHECK_MODE,
                    //                    CHECK_NUMBER = m1.CHECK_NUMBER,
                    //                    CHECK_TIME = m1.CHECK_TIME,
                    //                    CHECK_TYPE = m1.CHECK_TYPE,
                    //                    CHECK_USER_NAME = m2.TrueName,
                    //                    GET_NUMBER = m1.GET_NUMBER,
                    //                    REMARKS = m1.REMARKS,
                    //                    STATUS = m1.STATUS,
                    //                    TEMPLATE_ID = m1.TEMPLATE_ID
                    //                };
                    var queryData = m_Rep.GetList().Where(whereLambda);
                    pager.totalRows = queryData.Count();
                    //排序
                    queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                    return CreateModelList(ref queryData);
                    //return queryData.ToList();
                //}
            }
            catch (Exception )
            {
                return new List<S_SAMPLE_CHECKModel>(); 
            }
        }

		public virtual List<S_SAMPLE_CHECKModel> GetList(Expression<Func<S_SAMPLE_CHECK, bool>> whereLambda )
        {

            IQueryable<S_SAMPLE_CHECK> queryData = m_Rep.GetList(whereLambda); 
       
            return CreateModelList(ref queryData);
        }

		public virtual List<S_SAMPLE_CHECKModel> GetListByParentId(ref GridPager pager, string queryStr,object parentId)
        {
			return new List<S_SAMPLE_CHECKModel>();
		}

        public virtual List<S_SAMPLE_CHECKModel> CreateModelList(ref IQueryable<S_SAMPLE_CHECK> queryData)
        {
                List<S_SAMPLE_CHECKModel> modelList = (from r in queryData
                                                       select new S_SAMPLE_CHECKModel
                                                       {
                                                           CHECK_ID = r.CHECK_ID,
                                                           CHECK_USER_NAME = r.CHECK_USER.TrueName,
                                                           CHECKDETIAL = (from p in r.S_SAMPLE_CHECKDETAIL
                                                                          select new S_SAMPLEModel
                                                                          {
                                                                              SAMPLE_ID = p.S_SAMPLE.SAMPLE_ID,
                                                                              BATCH_CODE = p.S_SAMPLE.BATCH_CODE,
                                                                              MAKE_CODE = p.S_SAMPLE.MAKE_CODE,
                                                                              SAMPLE_CODE = p.S_SAMPLE.SAMPLE_CODE,
                                                                              RFID = p.S_SAMPLE.RFID,
                                                                              SAMPLE_TYPE = p.S_SAMPLE.SAMPLE_TYPE,
                                                                              CREATE_TIME = p.S_SAMPLE.CREATE_TIME,
                                                                              WEIGHT_STATUS = p.S_SAMPLE.WEIGHT_STATUS,
                                                                              WEIGHT = p.S_SAMPLE.WEIGHT,
                                                                              WEIGHT_USER_ID = p.S_SAMPLE.WEIGHT_USER_ID,
                                                                              WEIGHT_TIME = p.S_SAMPLE.WEIGHT_TIME,
                                                                              PRINT_COUNT = p.S_SAMPLE.PRINT_COUNT
                                                                          }).ToList(),
                                                           CHECK_MODE = r.CHECK_MODE,
                                                           CHECK_NUMBER = r.CHECK_NUMBER,
                                                           CHECK_USER_ID = r.CHECK_USER_ID,
                                                           CHECK_TIME = r.CHECK_TIME,
                                                           STATUS = r.STATUS,
                                                           CHECK_TYPE = r.CHECK_TYPE,
                                                           REMARKS = r.REMARKS,
                                                           GET_NUMBER = r.GET_NUMBER,
                                                           TEMPLATE_ID = r.TEMPLATE_ID,
                                                           APPROVAL_STATUS = r.APPROVAL_STATUS,
                                                           SAMPLE_TYPE=r.SAMPLE_TYPE

                                                       }).ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, S_SAMPLE_CHECKModel model)
        {
            try
            {
                S_SAMPLE_CHECK entity = m_Rep.GetById(model.CHECK_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new S_SAMPLE_CHECK();
               	entity.CHECK_ID = model.CHECK_ID;
				entity.CHECK_MODE = model.CHECK_MODE;
				entity.CHECK_NUMBER = model.CHECK_NUMBER;
				entity.CHECK_USER_ID = model.CHECK_USER_ID;
				entity.CHECK_TIME = model.CHECK_TIME;
				entity.STATUS = model.STATUS;
				entity.CHECK_TYPE = model.CHECK_TYPE;
				entity.REMARKS = model.REMARKS;
				entity.GET_NUMBER = model.GET_NUMBER;
				entity.TEMPLATE_ID = model.TEMPLATE_ID;
				entity.APPROVAL_STATUS = model.APPROVAL_STATUS;
  

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }



        public virtual bool Deletes(ref ValidationErrors errors,Expression<Func<S_SAMPLE_CHECK, bool>> whereLambda)
         {
		        try
				{
					using (DBContainer db = new DBContainer())
					{
				
							foreach (var entity in db.S_SAMPLE_CHECK.Where(whereLambda))
							{
								db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
							}

							if(db.SaveChanges()>0)
							{
								return true;
							}
							else
							{
								return false;
							}
			
					}
				}
				catch (Exception ex)
				{
					errors.Add(ex.Message);
					ExceptionHander.WriteException(ex);
					return false;
				}
        }

        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (m_DetailRep.Delete(a => a.CHECK_ID == id.ToString()) >= 1 && m_Rep.Delete(id) >= 1)
                    {
                        transactionScope.Complete();
                        return true;
                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
       

        public virtual bool Edit(ref ValidationErrors errors, S_SAMPLE_CHECKModel model)
        {
            try
            {
                S_SAMPLE_CHECK entity = m_Rep.GetById(model.CHECK_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                              				entity.CHECK_ID = model.CHECK_ID;
				entity.CHECK_MODE = model.CHECK_MODE;
				entity.CHECK_NUMBER = model.CHECK_NUMBER;
				entity.CHECK_USER_ID = model.CHECK_USER_ID;
				entity.CHECK_TIME = model.CHECK_TIME;
				entity.STATUS = model.STATUS;
				entity.CHECK_TYPE = model.CHECK_TYPE;
				entity.REMARKS = model.REMARKS;
				entity.GET_NUMBER = model.GET_NUMBER;
				entity.TEMPLATE_ID = model.TEMPLATE_ID;
				entity.APPROVAL_STATUS = model.APPROVAL_STATUS;
 


                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

      

        public virtual S_SAMPLE_CHECKModel GetById(object id)
        {
            if (IsExists(id))
            {
                S_SAMPLE_CHECK entity = m_Rep.GetById(id);
                S_SAMPLE_CHECKModel model = new S_SAMPLE_CHECKModel();
                model.CHECK_ID = entity.CHECK_ID;
                model.CHECK_MODE = entity.CHECK_MODE; 
                model.CHECK_NUMBER = entity.CHECK_NUMBER;
				model.CHECK_USER_ID = entity.CHECK_USER_ID;
				model.CHECK_TIME = entity.CHECK_TIME;
				model.STATUS = entity.STATUS;
				model.CHECK_TYPE = entity.CHECK_TYPE;
				model.REMARKS = entity.REMARKS;
				model.GET_NUMBER = entity.GET_NUMBER;
				model.TEMPLATE_ID = entity.TEMPLATE_ID;
				model.APPROVAL_STATUS = entity.APPROVAL_STATUS;
 
                return model;
            }
            else
            {
                return null;
            }
        }

        public virtual S_SAMPLE_CHECKModel GetItem(Expression<Func<S_SAMPLE_CHECK, bool>> whereLambda)
        {
            S_SAMPLE_CHECK entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            S_SAMPLE_CHECKModel model = new S_SAMPLE_CHECKModel();
            model.CHECK_ID = entity.CHECK_ID;
            model.CHECK_MODE = entity.CHECK_MODE;
            model.CHECK_NUMBER = entity.CHECK_NUMBER;
            model.CHECK_USER_ID = entity.CHECK_USER_ID;
            model.CHECK_TIME = entity.CHECK_TIME;
            model.STATUS = entity.STATUS;
            model.CHECK_TYPE = entity.CHECK_TYPE;
            model.REMARKS = entity.REMARKS;
            model.GET_NUMBER = entity.GET_NUMBER;
            model.TEMPLATE_ID = entity.TEMPLATE_ID;
            model.APPROVAL_STATUS = entity.APPROVAL_STATUS;

            return model;

        }


		 /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<S_SAMPLE_CHECKModel> list,ref ValidationErrors errors )
        {
          
            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
			 				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.CHECK_ID, "CHECK_ID");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.CHECK_MODE, "CHECK_MODE");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.CHECK_NUMBER, "CHECK_NUMBER");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.CHECK_USER_ID, "CHECK_USER_ID");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.CHECK_TIME, "CHECK_TIME");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.STATUS, "STATUS");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.CHECK_TYPE, "CHECK_TYPE");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.REMARKS, "REMARKS");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.GET_NUMBER, "GET_NUMBER");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.TEMPLATE_ID, "TEMPLATE_ID");
				 excelFile.AddMapping<S_SAMPLE_CHECKModel>(x => x.APPROVAL_STATUS, "APPROVAL_STATUS");
 
            //SheetName
            var excelContent = excelFile.Worksheet<S_SAMPLE_CHECKModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new S_SAMPLE_CHECKModel();
						 				  entity.CHECK_ID = row.CHECK_ID;
				  entity.CHECK_MODE = row.CHECK_MODE;
				  entity.CHECK_NUMBER = row.CHECK_NUMBER;
				  entity.CHECK_USER_ID = row.CHECK_USER_ID;
				  entity.CHECK_TIME = row.CHECK_TIME;
				  entity.STATUS = row.STATUS;
				  entity.CHECK_TYPE = row.CHECK_TYPE;
				  entity.REMARKS = row.REMARKS;
				  entity.GET_NUMBER = row.GET_NUMBER;
				  entity.TEMPLATE_ID = row.TEMPLATE_ID;
				  entity.APPROVAL_STATUS = row.APPROVAL_STATUS;
 
                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<S_SAMPLE_CHECKModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        S_SAMPLE_CHECK entity = new S_SAMPLE_CHECK();
                       						entity.CHECK_ID = model.CHECK_ID;
						entity.CHECK_MODE = model.CHECK_MODE;
						entity.CHECK_NUMBER = model.CHECK_NUMBER;
						entity.CHECK_USER_ID = model.CHECK_USER_ID;
						entity.CHECK_TIME = model.CHECK_TIME;
						entity.STATUS = model.STATUS;
						entity.CHECK_TYPE = model.CHECK_TYPE;
						entity.REMARKS = model.REMARKS;
						entity.GET_NUMBER = model.GET_NUMBER;
						entity.TEMPLATE_ID = model.TEMPLATE_ID;
						entity.APPROVAL_STATUS = model.APPROVAL_STATUS;
 
                        db.S_SAMPLE_CHECK.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
		  public void Dispose()
        { 
            
        }

	}
}
